<?php
/**
 * @abstract All the resources have to be one word
 * 
 */
class User_RoleController extends Clu_Controller_Action_Master
{
    
	public $m; //model

	public function init()
	{
		$this->m = new user_Model_Role();
		parent::init();
	}

    public function listAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer everything') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
        $this->viewParams['roleList'] = $this->m->getAllPermissions();
    }

    public function newAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer everything') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
	    
        $this->viewParams['form'] = new user_Form_NewRole();
        /*
        if (!$this->getRequest()->isPost() || !$this->viewParams['form']->isValid($_POST)) 
        {
            $this->renderError(null,t(504));
        	return;
        }
        */

        $data = array ("rname" => $this->_request->getParam("rname"));
        try 
        {
            $this->m->insertRaw($data, false /*no validation*/);
        }
        catch (Exception $e)
        {
            return;
        }
   
        $lastInsertId = $this->m->getAdapter()->lastInsertId();
        if($lastInsertId)
        {
        	$this->viewParams['operation'] = __('Create');
        	$this->presenceIdentifier = 1;
	        //$this->_forward("success", 'role' , 'user', array('lastInsertId' => $lastInsertId, 'lang' => 'en' ) );
        }
    }

    
    public function assignPermAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer everything') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
	    
        //get the list of all available permissions from config file /config/perm.config.php
        $allPermissions = Zend_Registry::get('permConfiguration');
        $rname = $this->_request->getParam('rname');

    	$rid = $this->_request->getParam("rid");
    	
    	if (!$r = $this->m->findByPrimary($rid))
        {
            $this->viewParams['errorMessage'] = __('Cannot find the requested article');
            $this->renderError(null,t(504));
        	return;
        }

        // if isPost then update 'perm' field
        if ($this->_request->isPost())
        {
            //get the form information
            $permArray = array();
            foreach ($allPermissions->moduleAllPermissions as $resource=>$p)
            {
            	$resourcePerms = $this->_request->getParam('role_'.$resource);
            	if ($resourcePerms)
            	{
            		//turn 'administer' to be many things
            		if (in_array('administer '.$resource, $resourcePerms))
            		{
            			foreach ($p as $availablePerm)
            				$permArray[] = sprintf($availablePerm, $resource);
            		}
            		else 
            		{ 
            		   	foreach ($resourcePerms as $checkedPerm)
    	   		     		$permArray[] = $checkedPerm;
            		}
            		
            	}
            }
			
            //save the permission
            if ($r->rname == 'GOD')
            	$permArray[] = 'administer everything';
            if ($this->m->saveRaw($r, array(
            		'rid' =>  $rid,
            		'perm' => implode (',', array_unique($permArray)),
            	), $rid, false)) // no need to validate
			{
	            $this->viewParams['successMessage'] = __("Permission saved <br/> New perm : ") . $r->perm;
	            $this->viewParams['perm'] = $permArray;
			}
			else
			{
				$this->viewParams['errorMessage'] = __("Could not save permissions");
				$this->viewParams['perm'] = explode (',', $r->perm );
			}
        }
        else {
            $this->viewParams['perm'] = explode (',', $r->perm );
        }                  
        $this->viewParams['allPermissions'] = $allPermissions;
        $this->viewParams['rid'] = $rid;
        $this->viewParams['rname'] = $rname;
        //$this->renderToHolder('role/assign-perm.phtml');
    }

    public function deleteAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer everything') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
	    
    	$rid = $this->_request->getParam("rid");
    	
    	if (!$r = $this->m->findByPrimary($rid))
        {                
            $this->viewParams['errorMessage'] = __('Cannot find the requested article');
            $this->renderError(null,t(504));
        	return;
        }
            
        if ($this->m->deleteByPrimary(array($rid)))
        {
            $this->viewParams['operation'] = __("Delete article");
            //$this->renderToHolder('common/success.phtml');
        }
		else
		{   
			$this->viewParams['errorMessage'] = __('Could not delete from DB');
            $this->renderError(null,t(504));
        	return;
		}   
    }

    
    public function successAction()
    {
    	$this->viewParams['operation'] = __('Create');
        //$this->renderToHolder('role/success.phtml');
    }

    public function bulkAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	//check user rights
       	if (strpos ($sess->userPermissions, 'administer everything') === false)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
	    
        $roles = $this->_request->getParam('roles');
        if (count($roles) > 0)
        {
            $action = $this->_request->getParam('bulkaction');
            if ($action === 'delete')
            {
				if ($this->m->deleteByPrimary($roles))
                {
                    $this->viewParams['operation'] = __("Delete roles");
        		    //$this->renderToHolder('common/success.phtml');
					return;
                }
            }
        }
    }
    
    
    //has been done with ajax
    /*
    public function editAction()
    {
    	$rid = $this->_request->getParam("rid");
    	
    	if (!$r = $this->m->findByPrimary($rid))
        {                
            $this->view->errorMessage = __('Cannot find the requested article');
            $this->renderToHolder('common/error.phtml');
            return;
        }
	
        //everything's fine. Continue editing
        $form = new user_Form_NewRole();
        $form->setAction('/en/user/role/edit');
        $form->submit->setLabel(__('Update'));
        
        //populate the data with 
		if (!$this->_request->isPost())
            $form->populate($r->toArray());
		
        else if ($form->isValid($_POST))
        {	
            $r->rname = $this->_request->getParam("rname");
            if ($r->save())
            {
                $this->view->operation = __("update Role");
                $this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->view->errorMessage = __("Could not update rolename to DB");
        }
        else 
        	$this->view->errorMessage = __("Input is not valid");

        $this->view->form = $form;
        $this->view->rid = $rid;
        $this->renderToHolder('role/edit.phtml');    
    }
    */
    
    
} 

?>